﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Game.Tools
{
    public class MapData
    {
        // 0：墙  1：路 2：钥匙 3：门 4：入口楼梯 5：宝箱 6 npc 7 敌人 8：出口楼梯
        public int id;
        
        public int[][] map;
        public PictureBox[,] mapPic;
        public int OpPicX,OpPicY; // 触发事件的地图块

        public static string _BASE_MAPPATH = "../map/";

        public static string savePath = "";

		public static string mapPath = "../map/map1.map";
		public int[][] oldMapData;
		
        public int[][] MapDataLoadTool(int level)
        {
			mapPath = "../map/map" + level + ".map";

			string jsonString = File.ReadAllText(mapPath);

			JObject jo = (JObject)JsonConvert.DeserializeObject(jsonString);
			JArray oldData = JArray.Parse(jo["originMapData"].ToString());
			JArray ja = jo["mapData"] != null ? JArray.Parse(jo["mapData"].ToString()) : oldData;
			int[][] mapData = new int[15][];
			int[][] oldMapData = new int[15][];

			for(int i = 0; i < 10; i++)
			{
				mapData[i] = new int[15];
				oldMapData[i] = new int[15];
				Console.WriteLine("开始初始化数据行" + i);
				for(int j = 0; j < 10; j++)
				{
					Console.WriteLine("开始初始化数据" + i + " : " + j);
					mapData[i][j] = (int)ja[i][j];
					oldMapData[i][j] = (int)oldData[i][j];
				}
			}

			return mapData;
		}

		/// <summary>
		/// 保存地图信息（保存状态）
		/// </summary>
		/// <param name="mapData">修改后的地图状态</param>
		/// <returns></returns>
		public bool SaveMapData(int[,] mapData)
		{
			//通过线程处理，防止写入时影响游戏进程
			Thread mapSaveThread = new Thread(MapDataSaveTool);
			mapSaveThread.Start(mapData);
			return true;
		}

        /// <summary>
        /// 写入新的地图信息
        /// </summary>
        /// <param name="mapData">地图信息（状态）</param>
        public void MapDataSaveTool(object mapData)
        {
            int[][] newMap = (int[][])mapData;
            JObject jo = JObject.FromObject(new { originMapData = oldMapData, mapData = mapData });
            string toJson = jo.ToString();

            //如果文件不存在，则创建；存在则覆盖
            System.IO.File.WriteAllText(savePath, toJson, Encoding.UTF8);
        }

        /// <summary>
        /// 保存地图信息（保存状态）
        /// </summary>
        /// <param name="mapData">修改后的地图状态</param>
        /// <returns></returns>
        public bool CreateMapData(int[][] mapData, int level)
        {
            //通过线程处理，防止写入时影响游戏进程
            savePath = _BASE_MAPPATH + "map" + level + ".map";
            Thread mapSaveThread = new Thread(MapDataCreateTool);
            mapSaveThread.Start(mapData);
            return true;
        }
        /// <summary>
        /// 写入新的地图信息
        /// </summary>
        /// <param name="mapData">地图信息（状态）</param>
        public void MapDataCreateTool(object mapData)
        {
            int[][] newMap = (int[][])mapData;
            JObject jo = JObject.FromObject(new { originMapData = newMap, mapData = newMap });
            string toJson = jo.ToString();
            
            toJson = StringFormat(toJson);
            Console.WriteLine(toJson);
            //如果文件不存在，则创建；存在则覆盖
            System.IO.File.WriteAllText(savePath, toJson, Encoding.UTF8);
        }

        public string StringFormat(string obj)
        {
            obj = obj.Replace(" ", "");
            obj = obj.Replace("\t", "");
            obj = obj.Replace("\n", "");
            obj = obj.Replace("\r", "");
            return obj;
        }
    }
}
